<template>
  <!-- 页面标题栏 -->
  <div class="mb-6 flex items-center">
    <el-button icon="ArrowLeft" @click="$router.back()"> 返回 </el-button>
    <h1 class="ml-4 text-2xl font-bold text-gray-900">AI图像模型配置</h1>
  </div>
  <!-- 主要内容区域 -->
  <div class="grid grid-cols-1 xl:grid-cols-3 gap-8">
    <!-- 左侧：基础信息卡片 -->
    <div class="xl:col-span-1">
      <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <!-- 卡片头部 -->
        <div class="px-6 py-4 color-blue-500">
          <h2 class="text-xl font-semibold ">基础信息</h2>
          <p class="text-sm mt-1">配置模型的基本信息</p>
        </div>
        <!-- 卡片内容 -->
        <div class="p-5 space-y-3">
          <!-- 模型厂商 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              模型厂商 <span class="text-red-500">*</span>
            </label>
            <el-select
              v-model="formData.manufacturer_id"
              placeholder="请选择模型厂商"
              class="w-full"
              size="large"
            >
              <el-option
                v-for="item in manufacturerList"
                :key="item.id"
                :label="item.name"
                :value="item.id"
              >
                <div class="flex items-center">
                  <span class="font-medium">{{ item.name }}</span>
                </div>
              </el-option>
            </el-select>
          </div>

          <!-- 模型类型 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              模型类型 <span class="text-red-500">*</span>
            </label>
            <el-select
              v-model="formData.model_type"
              placeholder="请选择模型类型"
              class="w-full"
              size="large"
            >
              <el-option
                v-for="(item, index) in modelTypeList"
                :key="index"
                :label="item"
                :value="Number(index)"
              />
            </el-select>
          </div>

          <!-- 模型名称 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              模型名称 <span class="text-red-500">*</span>
            </label>
            <el-input v-model="formData.name" placeholder="如：gpt-3.5-turbo" size="large">
              <template #prefix>
                <el-icon class="text-green-500"><Edit /></el-icon>
              </template>
            </el-input>
          </div>

          <!-- API地址 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2">
              API地址 <span class="text-red-500">*</span>
            </label>
            <el-input
              v-model="formData.api_url"
              placeholder="https://api.openai.com/v1/chat/completions"
              size="large"
            >
              <template #prefix>
                <el-icon class="text-green-500"><Link /></el-icon>
              </template>
            </el-input>
            <div class="mt-2 text-xs text-gray-500">
              <el-icon size="12" class="mr-1"><InfoFilled /></el-icon>
              请输入完整的API调用地址
            </div>
          </div>

          <!-- 排序权重 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2"> 排序权重 </label>
            <el-input-number
              v-model="formData.sort"
              :min="0"
              :max="9999"
              size="large"
              class="w-full"
            />
            <div class="mt-2 text-xs text-gray-500">
              <el-icon size="12" class="mr-1"><Sort /></el-icon>
              数值越小排序越靠前
            </div>
          </div>

          <!-- 备注说明 -->
          <div>
            <label class="block text-sm font-medium text-gray-700 mb-2"> 备注说明 </label>
            <el-input
              v-model="formData.remark"
              type="textarea"
              :rows="4"
              placeholder="添加模型的详细描述和使用说明..."
              maxlength="500"
              show-word-limit
            >
              <template #prefix>
                <el-icon class="text-green-500"><ChatLineRound /></el-icon>
              </template>
            </el-input>
          </div>
          <!-- 提交按钮 -->
          <div class="mt-6">
            <el-button type="primary" @click="handleSubmit" class="w-full">
              保存配置
            </el-button>
          </div>
        </div>
      </div>
    </div>

    <!-- 右侧：参数配置卡片 -->
    <div class="xl:col-span-2">
      <div class="bg-white rounded-xl shadow-sm border border-gray-100 overflow-hidden">
        <!-- 卡片头部 -->
        <div class="px-6 py-4">
          <h2 class="text-xl font-semibold t">调用参数配置</h2>
          <p class="text-sm mt-1">配置模型调用时的具体参数</p>
        </div>

        <!-- 卡片内容 -->
        <div class="p-6">
          <!-- 空状态 -->
          <div v-if="formData.params.length === 0" class="text-center py-16">
            <div
              class="inline-flex items-center justify-center w-20 h-20 bg-gradient-to-br from-blue-100 to-indigo-100 rounded-full mb-4"
            >
              <el-icon size="32" class="text-blue-600">
                <Setting />
              </el-icon>
            </div>
            <h3 class="text-lg font-medium text-gray-900 mb-2">暂无参数</h3>
            <p class="text-gray-500 text-sm mb-6">点击下面按钮添加第一个参数</p>
          </div>
          <!-- 参数列表 -->
          <div v-else class="space-y-4">
            <div
              v-for="(param, index) in formData.params"
              :key="index"
              class="border border-gray-200 rounded-lg p-5 hover:shadow-md transition-all duration-200"
            >
              <div class="flex justify-between items-start mb-4">
                <div class="flex items-center">
                  <div
                    class="w-8 h-8 bg-blue-100 rounded-full flex items-center justify-center mr-3"
                  >
                    <span class="text-blue-600 font-semibold text-sm">{{ index + 1 }}</span>
                  </div>
                  <div>
                    <h4 class="font-semibold text-gray-900">
                      {{ param.group ? `${param.group}.${param.name}` : param.name }}
                    </h4>
                    <p class="text-sm text-gray-500">{{ param.description }}</p>
                  </div>
                </div>
                <el-button
                  type="danger"
                  icon="Delete"
                  @click="removeParam(index)"
                  size="small"
                  circle
                  class="hover:scale-110 transition-transform"
                />
              </div>

              <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-4 gap-4">
                <!-- 参数分组 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    参数分组 <span class="text-red-500">*</span>
                  </label>
                  <el-select
                    v-model="param.group"
                    placeholder="选择分组"
                    size="default"
                    class="w-full"
                    filterable
                    allow-create
                  >
                    <el-option
                      v-for="group in parameterGroups"
                      :key="group"
                      :label="group"
                      :value="group"
                    />
                  </el-select>
                </div>

                <!-- 参数名 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    参数名 <span class="text-red-500">*</span>
                  </label>
                  <el-input v-model="param.name" placeholder="如：size" size="default" />
                </div>

                <!-- 参数类型 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2">
                    参数类型 <span class="text-red-500">*</span>
                  </label>
                  <DynamicInput
                    v-model="param.category"
                    :options="param.options || []"
                    @update:options="param.options = $event"
                  />
                </div>

                <!-- 默认值 -->
                <div>
                  <label class="block text-sm font-medium text-gray-700 mb-2"> 默认值 </label>
                  <el-input v-model="param.default"  default placeholder="输入默认值 可选"  size="default" ></el-input>
                </div>

                <!-- 参数描述 -->
                <div class="col-span-2">
                  <label class="block text-sm font-medium text-gray-700 mb-2"> 参数描述 </label>
                  <el-input
                    type="textarea"
                    v-model="param.description"
                    placeholder="参数描述"
                    size="default"></el-input>
                </div>
              </div>
            </div>
          </div>
       <!-- 底部添加按钮 -->
          <div class="px-6 py-4    flex justify-center">
            <el-button
              type="primary"
              icon="Plus"
              @click="addParam"
              size="default"
              round
              class="bg-blue-600 hover:bg-blue-700 text-white border-blue-600"
            >
              添加参数
            </el-button>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup lang="ts">
import { onMounted, reactive, ref, watch } from 'vue'
import { Setting, Edit, Link, ChatLineRound, Check } from '@element-plus/icons-vue'
import {
  addImageModelApi,
  updateImageModelApi,
  getManufacturerListApi,
  getImageModelTypeListApi,
  getImageModelDetailApi,
} from '@/api/ai'
import { ElMessage } from 'element-plus'
import DynamicInput from '@/components/DynamicInput/index.vue'
import router from '@/router'

const imageModelId = router.currentRoute.value.query.id as string


// 表单数据 - 仅用于界面展示
const formData = reactive({
  id: '',
  model_type: '',
  name: '',
  api_url: '',
  manufacturer_id: '',
  params: [] as ParamItem[],
  sort: 1000,
  status: 1,
  remark: '',
})

// 参数列表 - 用于三个输入框的动态参数配置
interface ParamItem {
  name: string
  category: string
  description: string
  group?: string
  default?: string
  options?: Array<{ label: string; value: any }>
}

// 厂商列表
const manufacturerList = ref<any[]>([])
const getManufacturerList = async () => {
  const { data } = await getManufacturerListApi({})
  manufacturerList.value = data
}
//模型类型
const modelTypeList = ref<any[]>([])
const getModelTypeList = async () => {
  const { data } = await getImageModelTypeListApi()
  modelTypeList.value = data
}

// 参数分组列表 - 动态管理
const parameterGroups = ref<string[]>([])

// 添加新的参数分组
const addParameterGroup = (group: string) => {
  if (group && !parameterGroups.value.includes(group)) {
    parameterGroups.value.push(group)
  }
}

// 监听参数分组变化，自动收集新的分组
watch(
  () => formData.params.map((p) => p.group),
  (newGroups) => {
    newGroups.forEach((group) => {
      if (group && !parameterGroups.value.includes(group)) {
        addParameterGroup(group)
      }
    })
  },
  { deep: true },
)

// 添加参数
const addParam = () => {
  formData.params.push({
    name: '',
    category: 'text',
    group: 'parameters',
    default: '',
    options: [],
    description: '',
  })
}

// 删除参数
const removeParam = (index: number) => {
  formData.params.splice(index, 1)
}

// 表单验证规则 - 仅界面展示
const formRules = {}

// 提交表单
const handleSubmit = async () => {
  await (formData.id ? updateImageModelApi(formData) : addImageModelApi(formData)).then(
    (res: any) => {
      ElMessage.success(res.message)
    },
  )
}
const handleClose = () => {
  // 清空表单数据
  Object.assign(formData, {
    id: '',
    model_type: '',
    name: '',
    api_url: '',
    manufacturer_id: '',
    params: [] as ParamItem[],
    sort: 1000,
    status: 1,
    remark: '',
  })
}
const setData = async () => {
 const {data} = await getImageModelDetailApi(imageModelId)
  Object.assign(formData, data)
}

onMounted(() => {
  getManufacturerList()
  getModelTypeList()
  setData()
})
</script>
